import { Canvas, Size, UITransform, director, profiler, sys } from "cc";
import { GameUtils } from "./GameUtils";
import { Platform } from "../Platform/PlatformWX";
import { WECHAT } from "cc/env";

export class CocosUtils {

    public static lerp (targetValue: number, curValue: number, ratio: number = 0.25) {
        let v = curValue;
        if (targetValue > curValue) {
            v = curValue + (targetValue - curValue) * ratio;
        } else if (targetValue < curValue) {
            v = curValue - (curValue - targetValue) * ratio;
        }
        
        return v;
    }
    
    public static clone (sObj: any) {
        if (sObj === null || typeof sObj !== "object") {
            return sObj;
        }

        var s = {};
        if (sObj.constructor === Array) {
            s = [];
        }

        for (var i in sObj) {
            if (sObj.hasOwnProperty(i)) {
                s[i] = this.clone(sObj[i]);
            }
        }

        return s;
    }

    private static isUint8Array(value: any): value is Uint8Array{
        return value instanceof Uint8Array;
    }

    public static ShowStatsInfo(): void {
        profiler.showStats();
    }

    public static HideStatsInfo(): void {
        profiler.hideStats();
        
    }   
    
    public static clamp(value, min, max): any {
        if(value < min) {
            return min;
        }
        if(value > max) {
            return max;
        }
 
        return value;
    }

    // 字符串转换为bytes
    public static StringToBytes(str: string):Uint8Array{
        const encoder = new TextEncoder();
        const bytes = encoder.encode(str);
        return bytes;
    }

    // 字节（bytes）转换为字符串
    public static BytesToString(bytes: Uint8Array): string{
        const decoder = new TextDecoder();          
        const strFromBytes = decoder.decode(bytes);
        return strFromBytes;
    }

     // let str = 'hello, world';
    //  let str = this.uint8ArrayToString(buf);
    //  let base64:string = GameUtils.base64encode(str);
    //  console.log('======编码======', base64);
    //  let base641: string = GameUtils.base64Decode(base64);
    //  console.log('======解码======', base641);
 
     
    //  let uint8Array = this.stringToUint8Array(base641);
    //  console.log('======uint8Array======', uint8Array);
    //  let res = LoginBackReq.decode(uint8Array);

    //将Unit8Array 编码
    public static Uint8ArrayToBase64(uint8Array: Uint8Array): string{
        let str:string = GameUtils.uint8ArrayToString(uint8Array);
        let base64:string = GameUtils.base64encode(str);
        return base64;
    }

    //将base64解码成 Unit8Array
    public static Base64ToUint8Array(base64: string): Uint8Array{
        let str:string = GameUtils.base64Decode(base64);
        let uint8Array:Uint8Array = GameUtils.stringToUint8Array(str);
        return uint8Array;
    }

    public static localStorageSet(key: string, value: any){
        // console.log('=======localStorageSet=======',key,value);
        let platform = sys.platform;
        if(platform === sys.Platform.WECHAT_GAME){
            Platform.inst.setStorageSync(key,value);
        }else if(sys.platform === sys.Platform.DESKTOP_BROWSER){
            localStorage.setItem(key,value);
        }
    }

    public static localStorageGet(key: string){
        let platform = sys.platform;
        let res = null;
        if(platform === sys.Platform.WECHAT_GAME){
            res = Platform.inst.getStorageSync(key);
        }else if(sys.platform === sys.Platform.DESKTOP_BROWSER){
            res = localStorage.getItem(key);
        }
        return res;
    }

    //截屏
    public static captureScreen(){

    //     screen.colorDepth


    //     // screen.captureScreen(() => {
    //     //     // 回调中的 data 是画面的纹理数据
    //     //     let texture = screen.getScreenshotTexture();
            
    //     //     // 如果需要将截屏的图片保存到设备，可以使用以下代码
    //     //     if (texture) {
    //     //         // 将纹理数据转换为图片并下载
    //     //         let canvas = document.createElement('canvas');
    //     //         canvas.width = texture.getContentSize().width;
    //     //         canvas.height = texture.getContentSize().height;
    //     //         let ctx = canvas.getContext('2d');
    //     //         ctx.drawImage(texture._webTexture._htmlElement, 0, 0);
                
    //     //         // 转换为 base64 图片数据
    //     //         let base64 = canvas.toDataURL('image/png');
                
    //     //         // 创建一个链接元素用于下载
    //     //         let a = document.createElement('a');
    //     //         a.href = base64;
    //     //         a.download = 'screenshot.png';
    //     //         a.click();
    //     //     }
    //     // });
    } 

    //获取当前运行的Canvas 尺寸
    public static winSize(): Size{
        return director.getScene().getComponentInChildren(Canvas).getComponent(UITransform).contentSize;
    }

    /**
     * 通过ip 或者域名 和 端口组成一个url
     * @param ip 
     * @param port 
     */
    public static getUrlByIdAndPort(ip:string, port: number): string{
        let url = "";
        let platform = sys.platform;
        if(platform === sys.Platform.WECHAT_GAME){
            url = `wss://${ip}:${port}`;
        }else{
            url = `ws://${ip}:${port}`;
        }
        return url;
    }
}

